﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RCREEE.Library;
using RCREEE.Library.Entities;

namespace RCREEE.Web
{
    public partial class UserSetup : System.Web.UI.Page
    {
        #region Properties
        private string SS_AllUsers = "AllUsers";
        private string SS_CurrentUser = "CurrentUser";
        private string SS_AllCountries = "AllCountries";
        private string SS_LangCode = "LanguageCode";

        public int LanguageCode
        {
            get
            {
                int langCode = 0;
                if (Session[SS_LangCode] != null)
                    int.TryParse(Session[SS_LangCode].ToString(), out langCode);
                return langCode;
            }
            set
            {
                Session[SS_LangCode] = value;
            }
        }
        public List<TinyItem> AllUsers
        {
            get
            {
                if (Session[SS_AllUsers] != null)
                    return (List<TinyItem>)Session[SS_AllUsers];

                return new List<TinyItem>();
            }
            set
            {
                Session[SS_AllUsers] = value;

            }
        }

        public List<TinyItem> AllCountries
        {
            get
            {
                if (Session[SS_AllCountries] != null)
                    return (List<TinyItem>)Session[SS_AllCountries];

                return new List<TinyItem>();
            }
            set
            {
                Session[SS_AllCountries] = value;

            }
        }
        public User CurrentUser
        {
            get
            {
                if (Session[SS_CurrentUser] != null)
                    return (User)Session[SS_CurrentUser];

                return new User();
            }
            set
            {
                Session[SS_CurrentUser] = value;

            }
        }
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //LanguageCode = (int)LanguagesEnum.English;
                ReloadUsers();

                BindCurrentUser();
            }
        }



        protected override void InitializeCulture()
        {
            if (LanguageCode > 0)
            {
                string languageId = "en-US";
                if (LanguageCode == (int)LanguagesEnum.French)
                    languageId = "fr-FR";
                if (LanguageCode == (int)LanguagesEnum.Arabic)
                    languageId = "ar-EG";
                if (LanguageCode == (int)LanguagesEnum.English)
                    languageId = "en-US";
                Thread.CurrentThread.CurrentCulture =
                CultureInfo.CreateSpecificCulture(languageId);

                Thread.CurrentThread.CurrentUICulture = new CultureInfo(languageId);
            }

            base.InitializeCulture();
        }

        private void ReloadUsers()
        {
            CurrentUser = new User();
            AllUsers = new List<TinyItem>();
            ReloadCountries();
            LoadAllUsers();
        }

        private void ReloadCountries()
        {
            AllCountries = DataManager.GetCountries(LanguageCode).Where(c => c.ID > 0).ToList();
            if (CurrentUser != null)
            {
                foreach (var item in AllCountries)
                {
                    TinyItem country = item;
                    if (!CurrentUser.UserPermissions.Any(c => c.CountryId == country.ID))
                    {
                        CurrentUser.UserPermissions.Add(new UserPermission
                                                            {
                                                                UserId = CurrentUser.UserId,
                                                                CountryId = country.ID,
                                                                Country = country,
                                                                CanAdd = false,
                                                                CanUpdate = false,
                                                                CanDelete = false
                                                            });
                    }
                }
            }
        }

        private void LoadAllUsers()
        {
            AllUsers = DataManager.GetAllUsers();
            listUsers.DataSource = AllUsers;
            listUsers.DataBind();
            //dataList.DataSource = AllUsers;
            //dataList.DataBind();
            //listUsers.
        }

        protected void BtnNew_Clicked(object sender, EventArgs e)
        {
            CurrentUser = new User();
            ReloadCountries();
            listUsers.SelectedIndex = -1;
            BindCurrentUser();
        }

        protected void BtnSave_Clicked(object sender, EventArgs e)
        {
            if (CurrentUser != null)
            {
                CurrentUser.FullName = txtFullName.Text;
                CurrentUser.PhoneNumber = txtPhoneNumber.Text;
                CurrentUser.MobileNumber = txtMobileNumber.Text;
                CurrentUser.Email = txtEmail.Text;
                CurrentUser.UserName = txtUserName.Text;
                CurrentUser.Password = txtPassword.Text;
                CurrentUser.IsAdmin = chkIsAdmin.Checked;

                if (DataManager.IsUserExist(CurrentUser))
                {
                    //if (!scriptManager.IsClientScriptBlockRegistered("CustomValidation"))
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "CustomValidation", "alert('A user with the same username is already exsist.');", true);
                    return;
                }

                RetriveDataFromGrid();
                DataManager.SaveUser(CurrentUser);
                ReloadUsers();
            }
        }

        private void RetriveDataFromGrid()
        {
            for (int i = 0; i < gridPermisions.Rows.Count; i++)
            {

                if (gridPermisions.Rows[i] != null && (gridPermisions.Rows[i].RowType == DataControlRowType.DataRow))
                {

                    var userPermission = CurrentUser.UserPermissions[gridPermisions.Rows[i].RowIndex];
                    var chkAdd = gridPermisions.Rows[i].FindControl("chkAdd") as CheckBox;
                    var chkUpdate = gridPermisions.Rows[i].FindControl("chkUpdate") as CheckBox;
                    var chkDelete = gridPermisions.Rows[i].FindControl("chkDelete") as CheckBox;

                    if (userPermission != null)
                    {
                        userPermission.CanAdd = chkAdd.Checked;
                        userPermission.CanUpdate = chkUpdate.Checked;
                        userPermission.CanDelete = chkDelete.Checked;
                    }
                }
            }
        }

        protected void ListUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            int userId;
            if (int.TryParse(listUsers.SelectedValue, out  userId) && userId > 0)
            {
                CurrentUser = DataManager.GetUserData(userId, LanguageCode);
                ReloadCountries();
                BindCurrentUser();
            }
        }

        private void BindCurrentUser()
        {
            if (CurrentUser != null)
            {
                txtFullName.Text = CurrentUser.FullName;
                txtPhoneNumber.Text = CurrentUser.PhoneNumber;
                txtMobileNumber.Text = CurrentUser.MobileNumber;
                txtEmail.Text = CurrentUser.Email;
                chkIsAdmin.Checked = CurrentUser.IsAdmin;
                txtUserName.Text = CurrentUser.UserName;
                txtPassword.Text = CurrentUser.Password;
                txtPassword.Attributes["value"] = CurrentUser.Password;
                txtConfirmPassword.Text = CurrentUser.Password;
                txtConfirmPassword.Attributes["value"] = CurrentUser.Password;
                gridPermisions.DataSource = CurrentUser.UserPermissions;
                gridPermisions.DataBind();
            }
        }


        protected void GridPermisions_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row != null)
            {

                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    var userPermission = (UserPermission)e.Row.DataItem;
                    var chkAdd = e.Row.FindControl("chkAdd") as CheckBox;
                    var chkUpdate = e.Row.FindControl("chkUpdate") as CheckBox;
                    var chkDelete = e.Row.FindControl("chkDelete") as CheckBox;

                    if (userPermission != null)
                    {
                        chkAdd.Checked = userPermission.CanAdd;
                        chkUpdate.Checked = userPermission.CanUpdate;
                        chkDelete.Checked = userPermission.CanDelete;
                    }
                }
                else
                    if (e.Row.RowType == DataControlRowType.Header)
                    {
                        var chkHeaderAdd = e.Row.FindControl("chkHeaderAdd") as CheckBox;
                        var chkHeaderUpdate = e.Row.FindControl("chkHeaderUpdate") as CheckBox;
                        var chkHeaderDelete = e.Row.FindControl("chkHeaderDelete") as CheckBox;

                        if (CurrentUser != null)
                        {
                            chkHeaderAdd.Checked = CurrentUser.UserPermissions.All(p => p.CanAdd);
                            chkHeaderUpdate.Checked = CurrentUser.UserPermissions.All(p => p.CanUpdate);
                            chkHeaderDelete.Checked = CurrentUser.UserPermissions.All(p => p.CanDelete);
                        }
                    }
            }
        }

        protected void Delete_Clicked(object sender, EventArgs e)
        {
            if (CurrentUser != null && CurrentUser.UserId > 0)
            {
                DataManager.DeleteUser(CurrentUser.UserId);
                ReloadUsers();
                CurrentUser = new User();
                ReloadCountries();
                BindCurrentUser();
            }
        }

        protected void ChkHeaderAdd_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chkHeaderAdd = (CheckBox)sender;
            if (chkHeaderAdd != null && CurrentUser != null && CurrentUser.UserPermissions != null)
            {
                foreach (UserPermission userPermission in CurrentUser.UserPermissions)
                {
                    userPermission.CanAdd = chkHeaderAdd.Checked;
                }
                gridPermisions.DataSource = CurrentUser.UserPermissions;
                gridPermisions.DataBind();
            }
        }

        protected void ChkHeaderUpdate_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chkHeaderUpdate = (CheckBox)sender;
            if (chkHeaderUpdate != null && CurrentUser != null && CurrentUser.UserPermissions != null)
            {
                foreach (UserPermission userPermission in CurrentUser.UserPermissions)
                {
                    userPermission.CanUpdate = chkHeaderUpdate.Checked;
                }
                gridPermisions.DataSource = CurrentUser.UserPermissions;
                gridPermisions.DataBind();
            }
        }

        protected void ChkHeaderDelete_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chkHeaderDelete = (CheckBox)sender;
            if (chkHeaderDelete != null && CurrentUser != null && CurrentUser.UserPermissions != null)
            {
                foreach (UserPermission userPermission in CurrentUser.UserPermissions)
                {
                    userPermission.CanDelete = chkHeaderDelete.Checked;
                }
                gridPermisions.DataSource = CurrentUser.UserPermissions;
                gridPermisions.DataBind();
            }
        }
    }
}